package com.sc.passbook.controller;

import com.sc.passbook.constant.Constant;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;

import static java.util.stream.Collectors.toSet;

/**
 * @author sc
 * Created on  2018/9/2
 */
@Controller
public class TokenUploadController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/token")
    public String tokenFileUpload(
            @RequestParam String merchantsId,
            @RequestParam String templateId,
            @RequestParam("file") MultipartFile file,
            RedirectAttributes attributes) throws IOException {
        if (StringUtils.isBlank(templateId) || file.isEmpty()) {
            attributes.addFlashAttribute("message", "para error");
            return "redirect:xxx";
        }

        File curr = new File(Constant.TOKEN_DIR + merchantsId);
        if (!curr.exists()) {
            curr.mkdir();
        }
        Path path = Paths.get(Constant.TOKEN_DIR, merchantsId, templateId);
        Files.write(path, file.getBytes());
        if (!writeTokenToRedis(path, templateId)) {
            attributes.addFlashAttribute("message", "write token error");
        } else {
            attributes.addFlashAttribute("message", "write token ok");
        }
        return "redirect:xxx";
    }

    private Boolean writeTokenToRedis(Path path,String key){
        Set<String> tokens;
        try {
            tokens=Files.lines(path).collect(toSet());

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        if(CollectionUtils.isNotEmpty(tokens)){
            redisTemplate.executePipelined(
                    (RedisCallback<Object>) connection->{
                        for (String token : tokens) {
                            connection.sAdd(key.getBytes(),token.getBytes());
                        }
                        return null;
                    });
            return true;
        }
        return false;
    }

}
